package tech.hdis.framework.security.session.imp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 缓存工具包
 *
 * @author 黄志文
 */
@Component
public class RedisSessionClient {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 设置缓存
     *
     * @param key   key
     * @param value value
     * @param time  time（秒为单位）
     */
    void set(String key, String value, long time) {
        BoundValueOperations<String, String> valueOps = stringRedisTemplate.boundValueOps(key);
        valueOps.set(value);
        if (time > 0) {
            valueOps.expire(time, TimeUnit.SECONDS);
        }
    }

    /**
     * 删除缓存
     *
     * @param key key
     */
    void del(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 查询缓存
     *
     * @param key key
     * @return value
     */
    String get(String key) {
        BoundValueOperations<String, String> valueOps = stringRedisTemplate.boundValueOps(key);
        return valueOps.get();
    }
}
